package network.internal.communication;

import static commons.Preconditions.checkIsPositive;
import static commons.Preconditions.checkNotNull;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import network.communication.Connection;
import network.communication.ConnectionFactory;
import network.io.InputStreamFactory;
import network.io.OutputStreamFactory;

public class DefaultConnectionFactory implements ConnectionFactory {

	private final InputStreamFactory<Socket, ObjectInputStream>		inputStreamFactory;
	private final OutputStreamFactory<Socket, ObjectOutputStream>	outputStreamFactory;
	private final int												transferMaxBufferSize;

	public DefaultConnectionFactory(final InputStreamFactory<Socket, ObjectInputStream> inputStreamFactory,
									final OutputStreamFactory<Socket, ObjectOutputStream> outputStreamFactory,
									final int tranferMaxBufferSize) {

		checkNotNull("inputStreamFactory must not be null.", inputStreamFactory);
		checkNotNull("outputStreamFactory must not be null.",
				outputStreamFactory);
		checkIsPositive("transferMaxBufferSize must be positive.",
				tranferMaxBufferSize);

		this.inputStreamFactory = inputStreamFactory;
		this.outputStreamFactory = outputStreamFactory;
		this.transferMaxBufferSize = tranferMaxBufferSize;
	}

	@Override
	public Connection createConnection(final Socket socket) throws IOException {
		checkNotNull("socket must not be null.", socket);
		return new DefaultConnection(inputStreamFactory, outputStreamFactory,
				socket, transferMaxBufferSize);
	}
}
